import { API_RPEFIX } from "./instance"
import axios, { AxiosRequestConfig, AxiosResponse } from "axios"
import { defineConfig, history } from "umi"
import { message } from "antd"

export interface IRespose<T = any> {
  msg: string | null
  code: string
  data: T
}

const whitelist: string[] = ["/sys/user/login"] // 白名单 不需要带token的接口

type IRequestConfig = AxiosRequestConfig

const { CancelToken } = axios

const pendingRequest: Map<string, any> = new Map()

/**
 * 生成唯一的请求key
 * @param config
 */
const getRequestKey = (config: AxiosRequestConfig): string => {
  const { url, method, data, params } = config
  return `${method}${url}${JSON.stringify(method === "GET" ? params : data)}`
}

/**
 * 将请求添加到请求队列里面
 * @param config
 */
const addPendingRequest = (config: AxiosRequestConfig): void => {
  const requestKey: string = getRequestKey(config)
  config.cancelToken =
    config.cancelToken ||
    new CancelToken((c) => {
      if (requestKey && !pendingRequest.has(requestKey)) {
        pendingRequest.set(requestKey, c)
      }
    })
}

/**
 * 移除请求队列中的重复请求
 * @param config
 */
const removePendingRequest = (config: AxiosRequestConfig): void => {
  const requestKey: string = getRequestKey(config)
  if (requestKey && pendingRequest.has(requestKey)) {
    const cancel = pendingRequest.get(requestKey)

    cancel(requestKey)
    pendingRequest.delete(requestKey)
  }
}

const instance = axios.create({
  baseURL: API_RPEFIX,
  timeout: 36 * 1000, // 设置超时时间36s
})

export interface IResposeItem<T = any> {
  code: number,
  data: T,
  message: string
}


// 请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    let newConfig: AxiosRequestConfig = config
    // (!newConfig.headers.Authorization) && (newConfig.headers.Authorization = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkZXZpY2VUeXBlIjoyLCJob3NwaXRhbFV1aWQiOiJiMjUxNGRhN2FlZDIxMWViOWM5MjAwMGMyOWZmNjFmYiIsInBob25lIjoiMTMyNDczMjg0NzUiLCJ1c2VySWQiOjMsInV1aWQiOiIwYjVkMzdlNDZkNGU0NWVkYTgwYjNkYWJkMjVlZjI3MyJ9.9K5-HQwmY_FpJ1lJ2_EC403B6v3WdMhu88l65b5lbfo")


    if (window.localStorage.getItem("token")) {
      newConfig.headers.Authorization = window.localStorage.getItem("token")
    } else {
      message.error("请重新登录")
      history.push({
        pathname: "/login",
        query: {},
      })
    }



    // newConfig.url = "/crMultidisciplinary" + newConfig.url
    try {
      removePendingRequest(newConfig)
      addPendingRequest(newConfig)
      return newConfig
    } catch (err) {
      removePendingRequest(newConfig)
      return Promise.reject(err)
    }
  },
  (err) => {
    removePendingRequest(err.config)
    if (axios.isCancel(err)) {
      console.log("Request canceled", err.message)
    } else {
      return Promise.reject(err)
    }
  }
)

// 响应拦截
instance.interceptors.response.use(
  (res: AxiosResponse<IResposeItem> | any) => {
    try {
      if (res.status === 200 && res.data && res.data.code === 200) {
        removePendingRequest(res.config)
        return res.data
      } else {
        return Promise.reject(res.data)
      }

    } catch (err) {
      return Promise.reject(err)
    }
  },
  (err) => Promise.reject(err)
)

export default instance
